package com.wjjun.base.ui.viewmodel

import android.os.Looper
import androidx.lifecycle.MutableLiveData

class BaseStateViewModel<T>  : BaseViewModel(){

    /**
     * 状态数据, 仅用于需要显示的数据, 不可对state进行双向绑定
     */
    private val state = MutableLiveData<T>()

    /**
     * 设置数据
     */
    fun setState(newData: T) {
        if (newData == state.value) {
            notifyChange()
            return
        }
        if (Looper.myLooper() == Looper.getMainLooper()) {
            state.value = newData!!
        } else {
            state.postValue(newData!!)
        }
    }

    /**
     * 获取数据
     */
    fun getState(): T? {
        return state.value
    }

    /**
     * 获取数据
     */
    fun editState(action: (T?) -> Unit) {
        action(state.value)
        notifyChange()
    }

}